package com.yingside.thread.dead;

import com.yingside.thread.test.MyThread1;

public class DeadLock {
    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();
        deadLock.init();
    }

    public void init(){
        MyThread myThread = new MyThread();
        Thread t1 = new Thread(myThread,"张三");
        Thread t2 = new Thread(myThread,"李四");
        t1.start();t2.start();
    }

    public class MyThread implements Runnable{

        private Object key1 = new Object();
        private Object key2 = new Object();
        private boolean flag = true;

        @Override
        public void run() {
            if(flag){
                flag = false;
                synchronized (key1){
                    System.out.println(Thread.currentThread().getName() + " 拿着key1 进入了！");

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (key2){
                        System.out.println(Thread.currentThread().getName() + " key2");
                    }
                }
            }
            else{
                flag = true;
                synchronized (key2){
                    System.out.println(Thread.currentThread().getName() + " 拿着key2 进入了！");

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (key1){
                        System.out.println(Thread.currentThread().getName() + " key1");
                    }
                }

            }

        }
    }
}
